

//
//  YZQWebViewViewController.m
//  SuperNews
//
//  Created by qiang on 16/1/12.
//  Copyright © 2016年 qiang. All rights reserved.
//

#import "YZQWebViewViewController.h"
#import "CoreDataManager.h"
#import "Collect.h"

@interface YZQWebViewViewController ()
@property (nonatomic, strong) NSMutableArray *imgArr;
@property (nonatomic, assign) NSInteger height;
@property (nonatomic, strong) UIAlertController *AlertC;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UILabel *labelTitle;

@property (nonatomic, strong) UIButton *collectBut;

@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) NSMutableArray *collectArr;
@property (nonatomic, assign) BOOL isCollect;
@end

@implementation YZQWebViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    self.collectArr = [NSMutableArray array];

    // Do any additional setup after loading the view.
    [self createSubviews];
    [self getData];
    
}

- (void)createSubviews
{
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 40, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 84)];
    [self.view addSubview: self.webView];
    
    self.labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width - 60, 40)];
    self.labelTitle.textAlignment = NSTextAlignmentCenter;
    self.labelTitle.font = [UIFont boldSystemFontOfSize:20];
    [self.view addSubview:self.labelTitle];
    
    self.collectBut = [[UIButton alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 60, 5, 25, 25)];
    [self.collectBut setImage:[UIImage imageNamed:@"iconfont-xingxing"] forState:UIControlStateNormal];
    [self.view addSubview:self.collectBut];
    
}

- (void)getData
{
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", self.docId];
    [AFNetTool getNetWithURL:url body:nil headFile:nil responseStyle:YZQJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        
        // 数组初始化
        self.imgArr = [NSMutableArray array];
        
        // 获取字典
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[responseObject objectForKey:self.docId]];
        // 可变字符串
        NSMutableString *bodyStr = [NSMutableString string];
        // 获取内容
        bodyStr = [dic objectForKey:@"body"];
        // 数组初始化
        NSMutableArray *tempArr = [NSMutableArray array];
        
        // 判断 将图片数据存入数组
        if ([[dic allKeys] containsObject:@"img"]) {
            tempArr = [dic objectForKey:@"img"];
            // 遍历数组
            for (NSDictionary *refDic in tempArr) {
                
                // 遍历 获取key
                for (NSString *key in refDic) {
                    /* 图片自适应 */
                    // 从pixel中取出数据
                    if ([[refDic allKeys] containsObject:@"pixel"] && ![[refDic valueForKey:@"pixel"] isEqualToString:@""]) {
                        // 获取数据
                        NSString *pixelS = [NSString stringWithFormat:@"%@",[refDic objectForKey:@"pixel"]];
                        
                        // 分解字符串(x*y)
                        NSArray *pixelArr = [pixelS componentsSeparatedByString:@"*"];
                        // 分别取出x,y
                        NSString *widthS = [pixelArr firstObject];
                        NSString *heightS = [pixelArr lastObject];
                        // 分别转成Integer 类型
                        NSInteger width = widthS.integerValue;
                        NSInteger height = heightS.integerValue;
                        // 适配高度
                        self.height = self.view.frame.size.width * height / width;
                    }
                    // 如果没有 高度等于450
                    if (![[refDic allKeys]containsObject:@"pixel"]) {
                        self.height = 450;
                     
                    }
                    // 通过key取出src中的数据
                    if ([key isEqualToString:@"src"]) {
                        
                        // 取出ref
                        NSRange range = [bodyStr rangeOfString:[refDic objectForKey:@"ref"]];
                        
                        // 如果不为空
                        if (range.length != NSNotFound) {
                            
                            // 拼接
                            NSString *picStr = [NSString stringWithFormat:@"<img src=\"%@\" width=\"375\" height=\"%ld\">", [refDic objectForKey:key], self.height];
                            // 拼入
                            bodyStr = [bodyStr stringByReplacingCharactersInRange:range withString:picStr].mutableCopy;
                          
                        }
                    
                    }
                }
            }
        }
        
        self.labelTitle.text = [dic objectForKey:@"title"];

        NSMutableArray *videoArr = [NSMutableArray array];
        /* 添加视频 */
        if ([[dic allKeys] containsObject:@"video"]) {
            videoArr = [dic objectForKey:@"video"];
            for (NSDictionary *refDic in videoArr) {
                for (NSString *key in refDic) {
                    if ( [key isEqualToString:@"url_mp4"] && ![[refDic valueForKey:@"url_mp4"] isEqualToString:@""] ) {
                        NSRange range1 = [bodyStr rangeOfString:[refDic objectForKey:@"ref"]];
                        if (range1.length != NSNotFound) {
                            NSString *videoStr = [NSString stringWithFormat:@"<video src=\"%@\" width=\"375\" height=\"240\" webkit-playsinline controls=\"preload\"></video>",[refDic objectForKey:key]];
                            bodyStr = [bodyStr stringByReplacingCharactersInRange:range1 withString:videoStr].mutableCopy;
                        }
                    }
                }
            }
        }
        [self.webView loadHTMLString:bodyStr baseURL:nil];
        [self selectCollectData];
        for (Collect *col in self.collectArr) {
            if ([col.title isEqualToString:self.labelTitle.text]) {
                [self.collectBut setImage:[UIImage imageNamed:@"iconfont-star"] forState:UIControlStateNormal];
                self.isCollect = YES;
            }
        }
        [self.collectBut addTarget:self action:@selector(collectButAction:) forControlEvents:UIControlEventTouchUpInside];
        
  
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
    }];
    
}

- (void)collectButAction:(UIButton *)sender
{
    if (NO == self.isCollect) {
        Collect *col = [NSEntityDescription insertNewObjectForEntityForName:@"Collect" inManagedObjectContext:self.coreDataManager.managedObjectContext];
        col.title = self.labelTitle.text;
        col.docId = self.docId;
        [self.coreDataManager saveContext];
        [self.collectBut setImage:[UIImage imageNamed:@"iconfont-star"] forState:UIControlStateNormal];
        self.isCollect = YES;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
        
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];

    } else {
       
        if (0 == self.collectArr.count) {
            [self selectCollectData];
        }
        
        for (Collect *col in self.collectArr) {
            if ([col.title isEqualToString:self.labelTitle.text]) {
                [self.coreDataManager.managedObjectContext deleteObject:col];
            }
        }
        self.isCollect = NO;
        [self.coreDataManager saveContext];
        [self.collectBut setImage:[UIImage imageNamed:@"iconfont-xingxing"] forState:UIControlStateNormal];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"取消收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
        
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];
    }
}

- (void)selectCollectData
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Collect" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    //    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"<#format string#>", <#arguments#>];
    //    [fetchRequest setPredicate:predicate];
    //    // Specify how the fetched objects should be sorted
    //    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"<#key#>"
    //                                                                   ascending:YES];
    //    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    //
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"error%@", error);
    }
    [self.collectArr setArray:fetchedObjects];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
